package com.example.aidldemo.aidl

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.os.RemoteException
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.aidldemo.R
import com.example.aidldemo.server.MyTestService
import com.google.android.material.snackbar.Snackbar


class MainActivity : AppCompatActivity(){
    private lateinit var mTvBind: TextView
    private val TAG = MainActivity::class.java.name
    private var testServer: IMyTestServer ?=null

    private val mConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            testServer = IMyTestServer.Stub.asInterface(service)
            try {
                val result: Int = testServer?.add(188, 288)
                Log.d(TAG, "--结果为--: $result")
                Snackbar.make(mTvBind,"--获取到的数据为--: $result",Snackbar.LENGTH_SHORT).show()
            } catch (e: RemoteException) {
                e.printStackTrace()
            }
        }

        override fun onServiceDisconnected(name: ComponentName) {
            try {
                testServer = null
            } catch (e: RemoteException) {
                e.printStackTrace()
            }
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mTvBind = findViewById(R.id.tv_bind)
        mTvBind.setOnClickListener{
           startService()
        }
    }

    private fun startService(){
        val intent = Intent(this@MainActivity, MyTestService::class.java)
        bindService(intent, mConnection, BIND_AUTO_CREATE)
    }

    override fun onDestroy() {
        super.onDestroy()
        testServer = null
        unbindService(mConnection)
    }

}